package com.tjetc.myservlet;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * @author gaoyongxiang
 * @version v1.0
 * @date 2025/9/1
 */
public class _1MyTomcat {
    public static void main(String[] args) throws IOException {
        // 1. 创建ServerSocket，监听8080端口
        ServerSocket serverSocket = new ServerSocket(8080);
        System.out.println("---------------tomcat启动 监听8080端口---------------");

        // 2. 等待连接
        while (!serverSocket.isClosed()) {
            // 一个socket对应一个请求
            Socket socket = serverSocket.accept();

            // 3. 接收请求
            InputStream inputStream = socket.getInputStream();
            // 包装成字符流
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));

            String data = "";
            System.out.println("------------开始接收请求数据--------------");
            // 循环读取
            while ((data = bufferedReader.readLine()) != null) {
                // 结束读？
                if (data.length() == 0) {
                    break;
                }
                System.out.println(data);
            }

            //4. 发送响应 响应格式应该是http协议
            OutputStream outputStream = socket.getOutputStream();
            // 封装响应头信息
            // 响应体和响应头之间有一个空行
            String respHeader = """
                    HTTP/1.1 200 OK
                    Content-Type: text/html;charset=utf-8
                    
                    """;
            String respMsg = respHeader + "张三";

            // 将数据写会给浏览器
            outputStream.write(respMsg.getBytes());
            outputStream.close();
            inputStream.close();
            socket.close();
        }
    }
}